package com.miplus.ccrm.core.service.commission;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.JSysUser;
import com.miplus.ccrm.core.controller.vo.commission.RepaymentDeParameterCfReqVo;
import com.miplus.ccrm.core.controller.vo.commission.RepaymentDetailsMonthPageReqVo;
import com.miplus.ccrm.core.controller.vo.commission.RepaymentDetailsMonthPageResVo;
import com.miplus.ccrm.core.pojo.FiCasesRepaymentDetails;
import com.miplus.ccrm.core.mapper.FiCasesRepaymentDetailsMapper;
import com.miplus.ccrm.core.pojo.FiCreditcases;
import com.miplus.ccrm.core.pojo.FiDistbatchHist;
import com.miplus.ccrm.core.service.ExportService;
import com.miplus.ccrm.core.service.crd.FiImportHistService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
* @author Yaohui
* @description 针对表【fi_cases_repayment_details(委案明细表)】的数据库操作Service实现
* @createDate 2025-03-11 10:08:41
*/
@Slf4j
@Service
public class FiCasesRepaymentDetailsServiceImpl extends MPJBaseServiceImpl<FiCasesRepaymentDetailsMapper, FiCasesRepaymentDetails>
    implements FiCasesRepaymentDetailsService{

    @Resource
    private ExportService exportService;


    @Resource
    private FiImportHistService fiImportHistService;

    @Override
    public IPage<RepaymentDetailsMonthPageResVo> monthlyPage(RepaymentDetailsMonthPageReqVo reqVo) {
        //不能和分配批次表关联，目前批次ID不唯一，导致数据增多。批次ID。
        MPJLambdaWrapper<FiCasesRepaymentDetails> fiCasesRepaymentDetailsMPJLambdaWrapper = getQueryWrapper(reqVo);
        return selectJoinListPage(new Page<>(reqVo.getPageNum(),reqVo.getPageSize()), RepaymentDetailsMonthPageResVo.class,
                fiCasesRepaymentDetailsMPJLambdaWrapper
                       // .leftJoin(FiDistbatchHist.class,FiDistbatchHist::getBatchid,FiCasesRepaymentDetails::getDistbatchid)
                        .leftJoin(FiCreditcases.class, FiCreditcases::getCreditcaseid,FiCasesRepaymentDetails::getCasesDetailsId)
                        .selectAs("fun_getnames('COLLECT.STATUS',t.status)", RepaymentDetailsMonthPageResVo::getStatusDsc)
                        .selectAs("fun_getnames('COMMISSION.RULE',t.commission_rule)", RepaymentDetailsMonthPageResVo::getCommissionRuleDsc)
                        .selectAs("fun_getnames('SORTING.QUEUE',t.disttag)", RepaymentDetailsMonthPageResVo::getDisttag)
                        .selectAs("(select g.grpname from sys_grp g where g.grpid=t.sendtodept)", RepaymentDetailsMonthPageResVo::getSendtodeptdsc)
                        .selectAs("(select name from sys_user where usrid = t.sendtousr)",RepaymentDetailsMonthPageResVo::getSendtousr)
                        .selectAs(FiCreditcases::getDistbatchid,RepaymentDetailsMonthPageResVo::getBatchname)
                        .selectAll(FiCasesRepaymentDetails.class)
                        .orderByDesc(FiCasesRepaymentDetails::getCreationTime)
        );
    }

    @Override
    public CmdResVo monthlyExcel(JSysUser user, RepaymentDetailsMonthPageReqVo paras, HttpServletResponse response) {
        String $usrid=user.getUsrid();
        IPage<RepaymentDetailsMonthPageResVo> pages = monthlyPage(paras);

        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"每月在委案件明细报表");
        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );
        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                $usrid
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            fiImportHistService.AddExportHist(
                    resVo.getKeyId(),
                    $usrid,
                    exptempid,
                    filename,
                    okcount
            );
        }

        return resVo;
    }

    private MPJLambdaWrapper getQueryWrapper(RepaymentDetailsMonthPageReqVo reqVo){

        return new MPJLambdaWrapper<>(FiCasesRepaymentDetails.class)
                .eq(JPubUtils.IsNotEmpty(reqVo.getCreditcaseid()), FiCasesRepaymentDetails::getCreditcaseid, reqVo.getCreditcaseid())
                .in(JPubUtils.IsNotEmpty(reqVo.getSendtodept()), FiCasesRepaymentDetails::getSendtodept, reqVo.getSendtodept())
                .in(JPubUtils.IsNotEmpty(reqVo.getSendtousr()), FiCasesRepaymentDetails::getSendtousr, reqVo.getSendtousr())
                .in(JPubUtils.IsNotEmpty(reqVo.getDisttag()), FiCasesRepaymentDetails::getDisttag, reqVo.getDisttag())
                .in(JPubUtils.IsNotEmpty(reqVo.getCustnumberlist()), FiCasesRepaymentDetails::getCustomernumber, reqVo.getCustnumberlist())
                .in(JPubUtils.IsNotEmpty(reqVo.getCreditcaseidlist()), FiCasesRepaymentDetails::getCreditcaseid, reqVo.getCreditcaseidlist());
    }

    @Transactional
    @Override
    public CmdResVo parameterConfig(String usrid,RepaymentDetailsMonthPageReqVo qParameter,RepaymentDeParameterCfReqVo reqVo) {

        try {
            MPJLambdaWrapper<FiCasesRepaymentDetails> fiCasesRepaymentDetailsMPJLambdaWrapper = getQueryWrapper(qParameter);

            fiCasesRepaymentDetailsMPJLambdaWrapper.eq(FiCasesRepaymentDetails::getCheckout,0);

            FiCasesRepaymentDetails repaymentDetails=new FiCasesRepaymentDetails();
            repaymentDetails.setBaseCommission(reqVo.getBaseCommission());
            repaymentDetails.setConversionCoefficient(reqVo.getConversionCoefficient());
            repaymentDetails.setForCommissionCoefficient(reqVo.getForCommissionCoefficient());
            repaymentDetails.setMddt(new Date());
            repaymentDetails.setMdusr(usrid);
            repaymentDetails.setAnAccountRemark(reqVo.getAnAccountRemark());
            if(reqVo.getIsquydist()==0){
                update(repaymentDetails,new MPJLambdaWrapper<>(FiCasesRepaymentDetails.class)
                        .in(FiCasesRepaymentDetails::getCasesDetailsId,reqVo.getCasesDetailsIdList()));
            }else {
                update(repaymentDetails,fiCasesRepaymentDetailsMPJLambdaWrapper);
            }

            return new CmdResVo(1,"ok");
        } catch (Exception e) {
            log.info("parameterConfig>e:{}",e);
            throw new RuntimeException("配置异常");
        }
    }
}




